#include "../sources/thread.h"
long count=0;
void* func(void* param){
	int n=*(int*)param;
	int* h=malloc(sizeof(int));
	free(param);
	if(n==0){
		*h=0;
		return h;
	}
	if(n==1){
		*h=1;
		return h;
	}
	int* p=malloc(sizeof(int));*p=n-1;
	count++;
	int* q=malloc(sizeof(int));*q=n-2;
	thread_t thread1,thread2;
	int* r1=(int*)malloc(sizeof(int));
	thread_create(&thread1,func,q);
	final_thread_join(thread1,&r1);
	int* r2=(int*)malloc(sizeof(int));
	thread_create(&thread2,func,p);
	final_thread_join(thread2,&r2);
	*h=*r1+*r2;
	free(r1);
	free(r2);
	return h;
}
int main(int argc,void * argv[]){
	int* n=malloc(sizeof(int));
	*n=atoi(argv[1]);
	int* result;
	thread_t thread1;
	thread_create(&thread1,func,n);
	thread_join(thread1,&result);
	printf("result after %ld threads = %d\n",count,*result);
	free(result);

	return 0;
}
